<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Ixudra\Curl\Facades\Curl;

class WechatController extends Controller
{
    const APPID="wx935cdb3a2a049e5c";

    const APPSECRET="083e078b99a9b22e26d7d223ecd90c34";

    public function __construct()
    {
        $this->appId = config('xxx');
        $this->appSecret = config('xxx');
    }

    public function code(){
        $this->getQCode();exit;
        $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.WechatController::APPID.'&redirect_uri='.urlencode('http://192.168.1.10/home/wechat/getcode').'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
//        var_dump($url);
        $curl = Curl::to($url)
            ->get();

        $curl = json_decode($curl, true);
//        var_dump($curl);
        //微信浏览器
//        return redirect($url);
    }

    public function getcode(){
        $code=request()->get('code');
        //添加code到缓存
        Cache::put('code', $code, 120);
        $this->saveAndReturnUserInfo();
    }

    public function saveAndReturnUserInfo()
    {
        $code = Cache::get('code');

        if ($code) {

            //获取用户的openId
            $openId = $this->getOpenId($code);

            //获取用户基本信息
            $user_info = $this->getUserInfo($openId);
            var_dump($user_info);exit;

            //绑定获取的微信信息到当前用户
            //更新openid到用户表，重新缓存用户信息
            return $user_info;
        }

        //完成授权跳转到之前的请求地址
        //授权是一般是在中间件中完成
        return redirect(request('url'));
    }

    /**
     * 获取用户的openId
     *
     * @param $code
     * @return mixed
     */
    private function getOpenId($code)
    {
        //从redis中获取有效的access_token
        $access_token = Cache::get('access_token');

        if ($access_token) return $access_token;

        $curl = Curl::to('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.WechatController::APPID.'&secret='.WechatController::APPSECRET.'&code='.$code.'&grant_type=authorization_code')
            ->get();

        $curl = json_decode($curl, true);

        //重新设置缓存，有效期120分钟
        Cache::put('access_token', $curl['access_token'], 120);

        return $curl['openid'];
    }

    /**
     * 获取用户详情
     *
     * @param $openId
     * @return mixed
     */
    private function getUserInfo($openId)
    {
        //从redis中获取有效的access_token
        $access_token = Cache::get('access_token');

        $curl = Curl::to('https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openId.'&lang=zh_CN')
            ->get();

        return $curl = json_decode($curl, true);
    }

    public function getAccessToken(){
        $curl = Curl::to('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.WechatController::APPID.'&secret='.WechatController::APPSECRET)
        ->get();
        $curl = json_decode($curl, true);

        return $curl['access_token'];
    }

    public function getQCode(){
        $token=$this->getAccessToken();
        $post_data = [
            "expire_seconds"=> 2592000,
            "action_name"=> "QR_SCENE",
            "action_info"=> [
                "scene"=> [
                    "scene_id"=>123,
//                    'scene_str'=>"test"
                ]
            ]
        ];
//        $curl = Curl::to("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$token)
        $data= Curl::to("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$token)
            ->withData(json_encode($post_data))
            ->post();
        $data=json_decode($data, true);
        $tiket=$data['ticket'];
        var_dump($data['url']);
        $img=Curl::to("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($tiket))->get();
//        $img = json_decode($img, true);
//        var_dump($img);
        return file_put_contents("./upload/qcode.jpg",$img);
    }


}
